package com.pro.mianshiti;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * @author Sanmier
 * @version 1.0
 * @date 2024/4/23
 */
public class Service3 {
    public Map<Long, String> get(List<Long> userIds) {
        // 创建一个线程池，用于并行处理多个批次的用户ID
        ThreadPoolExecutor executor = new ThreadPoolExecutor(20, 20, 0L, TimeUnit.MILLISECONDS, new SynchronousQueue<>());
        List<Future<Map<Long, String>>> futures = new ArrayList<>();

        // 将用户ID列表分批，并且提交到线程池中处理
        for (int i = 0; i < userIds.size(); i += 50) {
            List<Long> subList = userIds.subList(i, Math.min(i + 50, userIds.size()));
            Callable<Map<Long, String>> task = new Service3.UserMapTask(subList);
            Future<Map<Long, String>> future = executor.submit(task);
            futures.add(future);
        }

        // 等待所有批次的处理结果
        Map<Long, String> resultMap = new HashMap<>();
        for (Future<Map<Long, String>> future : futures) {
            try {
                resultMap.putAll(future.get()); // 将每个批次的结果合并到总结果中
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace(); // 异常处理，这里简单打印了异常信息
            }
        }

        executor.shutdown(); // 关闭线程池
        return resultMap;
    }

    // Callable 任务，用于获取用户昵称
    static class UserMapTask implements Callable<Map<Long, String>> {
        private List<Long> userIds;

        public UserMapTask(List<Long> userIds) {
            this.userIds = userIds;
        }

        @Override
        public Map<Long, String> call() throws Exception {
            // 模拟调用 UserService.getUserMap() 方法
            UserService3 userService = new UserService3();
            return userService.getUserMap(userIds);
        }
    }

    public static void main(String[] args) {
        Service service = new Service();
        List<Long> userIds = new ArrayList<>();
        for (long i = 1; i <= 1000; i++) {
            userIds.add(i);
        }

        long startTime = System.currentTimeMillis();
        Map<Long, String> result = service.get(userIds);
        long endTime = System.currentTimeMillis();
        System.out.println("耗时：" + (endTime - startTime) + "ms");
        System.out.println("结果数量：" + result.size());
        System.out.println("结果：" + result);
    }
}

class UserService3 {
    public Map<Long, String> getUserMap(List<Long> userIds){
        if(userIds == null || userIds.size() > 50){
            throw new RuntimeException("userids more than 50");
        }
        Map<Long, String> result = new HashMap();
        for(Long userId : userIds){
            result.put(userId, "test");
        }
        return result;
    }
}
